import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Image, Popconfirm, Select } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { history } from 'umi';
import FormItem from 'antd/lib/form/FormItem';
import UploadImg from '@/components/UploadImg';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import { queryRule, updateRule, addRule, removeRule, setRule } from './service';
import styles from '../../../../global.less';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const handleSet = async (selectedRows, actionRef) => {
  const hide = message.loading('正在配置');
  if (!selectedRows) return true;

  try {
    await setRule(selectedRows);
    hide();
    message.success('配置成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('配置失败，请重试');
    return false;
  }
};
const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [count, setCount] = useState();
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [facePicture, setFacePicture] = useState(null);
  const handleSetFacePicture = (payload) => {
    setFacePicture(payload.url);
  };
  const { Option } = Select;
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',

      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },

    {
      title: '是否默认启用',
      dataIndex: 'isDefault',
      valueEnum: {
        true: {
          text: '是',
          status: 'success',
        },
        false: {
          text: '否',
          status: 'error',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择是否默认启用">
            <Option value={true}>是</Option>
            <Option value={false}>否</Option>
          </Select>
        );
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        1: {
          text: '积分支付',
        },
        2: {
          text: '现金支付',
        },
        3: {
          text: '扫码支付',
        },
        4: {
          text: '银行卡支付',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择类型">
            <Option value={1}>积分支付</Option>
            <Option value={2}>现金支付</Option>
            <Option value={3}>扫码支付</Option>
            <Option value={4}>银行卡支付</Option>
          </Select>
        );
      },
    },
    {
      title: '图标',
      dataIndex: 'icon',
      render: (_, record) => {
        return <Image style={{ maxHeight: '40px' , maxWidth: '40px'}} src={_} />;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            {stepFormValues ? (
              <FormItem name="icon">
                <UploadImg
                  imgUrl={facePicture}
                  showImgUrl={facePicture}
                  subpath="icon"
                  handleSetFacePicture={handleSetFacePicture}
                />
              </FormItem>
            ) : (
              <FormItem name="icon">
                <UploadImg subpath="icon" handleSetFacePicture={handleSetFacePicture} />
              </FormItem>
            )}
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                handleUpdateModalVisible(true);
                handleModalVisible(true);
                setStepFormValues(record);
                setFacePicture(record.icon);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
            <Popconfirm
              placement="top"
              title="确定要删除吗?"
              onConfirm={() => {
                handleSet(record.id, actionRef);
              }}
              okText="确定"
              cancelText="取消"
            >
              <a>设为默认</a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              placement="top"
              title="确定要删除吗?"
              onConfirm={() => {
                handleRemove(record.id, actionRef);
              }}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
            <Divider type="vertical" />
            <a
              onClick={() => {
                history.push(`ConfigurationDetails`);
              }}
            >
              支付配置
            </a>
          </>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="渠道信息列表"
        actionRef={actionRef}
        rowKey="id"
        bordered
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleUpdateModalVisible(false);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(params) => {
          const { list, total } = params;
          setCount(total);
          return list;
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />

      <CreateForm
        width={800}
        title={updateModalVisible ? '修改渠道信息' : '新建渠道信息'}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.icon = facePicture;
            updateModalVisible ? (value.id = stepFormValues.id) : null;
            const success = updateModalVisible ? await handleUpdate(value) : await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: updateModalVisible === true ? stepFormValues : null,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
